import { computed, h, ref, unref } from 'vue';

import { type VbenFormSchema, z } from '@vben/common-ui';

import { Spin } from 'ant-design-vue';

import { getCaptcha } from '#/api/core/auth';

export const useFormSchema = () => {
  const captcha = ref<string>('');
  const uuid = ref<string>('');
  // 验证码加载动画
  const spinning = ref(false);

  // 加载图形验证码
  const loadCaptcha = async () => {
    const { img, uuid: uid } = await getCaptcha();
    spinning.value = false;
    captcha.value = img;
    uuid.value = uid;
  };

  // 登录表单
  const formSchema = computed<VbenFormSchema[]>(() => {
    return [
      {
        fieldName: 'userPhone',
        component: 'VbenInput',
        componentProps: {
          placeholder: '请输入电话号码',
        },
        rules: z.string().regex(/^1\d{10}$/, { message: '手机号格式不正确' }),
        defaultValue: '15900001231',
      },
      {
        fieldName: 'userPwd',
        component: 'VbenInputPassword',
        rules: z
          .string()
          .min(6, { message: '密码6 - 16位' })
          .max(16, { message: '密码6 - 16位' }),
        defaultValue: '123456',
      },
      {
        fieldName: 'userCaptcha',
        component: 'VbenInput',
        suffix: () =>
          h(
            'div',
            {
              style: {
                width: '80px',
                marginLeft: '5px',
              },
            },
            h(
              Spin,
              {
                spinning: unref(spinning),
              },
              () =>
                h('img', {
                  src: `data:image/png;base64,${unref(captcha)}`,
                  style: {
                    height: '36px',
                  },
                  async onClick() {
                    spinning.value = true;
                    await loadCaptcha();
                  },
                }),
            ),
          ),
        componentProps: {
          placeholder: '请输入图形验证码',
        },
        rules: z.string().min(1, { message: '请输入图形验证码' }),
      },
    ];
  });

  return {
    loadCaptcha,
    formSchema,
    uuid,
  };
};
